#include "baseSession.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/epoll.h>

extern int io_epfd;

BaseSession::BaseSession() : thread_index(-1), status(INACTIVATE)
{
    sock_fd = -1;
    version = std::chrono::steady_clock::now();
}

BaseSession::~BaseSession()
{
    if (sock_fd != -1)
    {
        close(sock_fd);
        sock_fd = -1;
    }
    return;
}

void BaseSession::init_session(int _sock_fd, std::string ip)
{
    status = ACTIVATE;
    thread_index = -1;
    sock_fd = _sock_fd;
    peer_ip = ip;
    return;
}

int BaseSession::send_data(unsigned char *data, int len)
{
    if (this->sock_fd < 0 || data == NULL || len <= 0)
        return -1;

    shared_ptr<WriteData> write_data = make_shared<WriteData>();
    write_data->data = data;
    write_data->len = len;
    this->write_buffer.push_task(write_data);
    modify_event(io_epfd, this->sock_fd, EPOLLET | EPOLLOUT | EPOLLERR, EPOLL_CTL_MOD);
    return 0;
}

int BaseSession::recv_data(unsigned char *buff, int len)
{
    int n = 0, data_len = 0;
    while (1)
    {
        n = recv(sock_fd, buff + data_len, len - data_len, 0);
        if (n < 0)
        {

            if (errno == EAGAIN) // no data
            {
                return data_len;
            }
            printf("recv return %d:%s\n", n, strerror(errno));
            return -1;
        }
        if (n == 0)
        {
            printf("peer close\n");
            return -1;
        }
        data_len += n;
    }

    return 0;
}